<?php
// 数据库配置
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'model');

// 创建数据库连接
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS);
if ($conn->connect_error) die("连接失败: " . $conn->connect_error);

// 创建数据库和表
$conn->query("CREATE DATABASE IF NOT EXISTS ".DB_NAME." CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$conn->select_db(DB_NAME);
$conn->query("CREATE TABLE IF NOT EXISTS transitions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    prefix VARCHAR(50) CHARACTER SET utf8mb4 NOT NULL,
    suffix VARCHAR(50) CHARACTER SET utf8mb4 NOT NULL,
    count INT DEFAULT 1,
    UNIQUE KEY unique_transition (prefix, suffix)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// 设置字符集
$conn->set_charset("utf8mb4");

// 处理表单提交
$message = '';
$generated = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['train'])) {
        if (!empty($_POST['training_text'])) {
            trainModel($_POST['training_text']);
            $message = "训练完成！已分析 " . mb_strlen($_POST['training_text']) . " 个字符";
        } else {
            $message = "请提供训练文本";
        }
    } elseif (isset($_POST['generate'])) {
        $length = max(5, min(200, (int)$_POST['length']));
        $generated = generateText($length);
    } elseif (isset($_POST['reset'])) {
        $conn->query("TRUNCATE TABLE transitions");
        $message = "模型已重置";
    }
}

// 训练模型函数
function trainModel($text) {
    global $conn;
    
    // 清理文本：移除多余空格、标点符号等
    $text = preg_replace('/\s+/u', ' ', $text);
    $text = preg_replace('/[^\p{Han}\p{P}\s]/u', '', $text);
    $text = trim($text);
    
    // 分割文本为字符数组
    $chars = [];
    preg_match_all('/./u', $text, $chars);
    $chars = $chars[0];
    
    if (count($chars) < 2) {
        $message = "需要更多训练数据";
        return;
    }
    
    // 准备SQL语句
    $stmt = $conn->prepare("INSERT INTO transitions (prefix, suffix, count) 
            VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE count = count + 1");
    if (!$stmt) {
        error_log("准备语句失败: " . $conn->error);
        return;
    }
    
    $stmt->bind_param("ss", $prefix, $suffix);
    
    // 学习字符关系
    for ($i = 0; $i < count($chars) - 1; $i++) {
        $prefix = $chars[$i];
        $suffix = $chars[$i + 1];
        
        if (!$stmt->execute()) {
            error_log("执行失败: " . $stmt->error);
        }
    }
    $stmt->close();
}

// 文本生成函数
function generateText($length) {
    global $conn;
    
    // 检查是否有训练数据
    $result = $conn->query("SELECT COUNT(*) as total FROM transitions");
    if (!$result) {
        return "数据库查询错误";
    }
    
    $row = $result->fetch_assoc();
    if ($row['total'] == 0) return "请先训练模型";
    
    // 随机选择起始字符
    $result = $conn->query("SELECT prefix FROM transitions 
                           WHERE prefix REGEXP '[\p{Han}]' 
                           ORDER BY RAND() LIMIT 1");
    if (!$result || $result->num_rows == 0) {
        $result = $conn->query("SELECT prefix FROM transitions ORDER BY RAND() LIMIT 1");
    }
    
    if (!$result || $result->num_rows == 0) {
        return "找不到起始字符";
    }
    
    $current = $result->fetch_assoc()['prefix'];
    $output = [$current];
    
    // 生成后续字符
    for ($i = 1; $i < $length; $i++) {
        $next = getNextChar($current);
        if (!$next) break;
        
        $output[] = $next;
        $current = $next;
    }
    
    return implode('', $output);
}

// 获取下一个字符
function getNextChar($prefix) {
    global $conn;
    
    // 获取可能的后续字符
    $stmt = $conn->prepare("SELECT suffix, count FROM transitions WHERE prefix = ?");
    if (!$stmt) return null;
    
    $stmt->bind_param("s", $prefix);
    if (!$stmt->execute()) return null;
    
    $result = $stmt->get_result();
    $options = [];
    $total = 0;
    
    while ($row = $result->fetch_assoc()) {
        $options[$row['suffix']] = $row['count'];
        $total += $row['count'];
    }
    
    if ($total === 0) return null;
    
    // 基于权重随机选择
    $rand = mt_rand(1, $total);
    foreach ($options as $char => $count) {
        $rand -= $count;
        if ($rand <= 0) return $char;
    }
    
    return array_key_first($options);
}

// 获取训练数据统计
function getStats() {
    global $conn;
    $stats = ['prefix_count' => 0, 'transition_count' => 0];
    
    // 查询前缀数量
    $result = $conn->query("SELECT COUNT(DISTINCT prefix) as prefix_count FROM transitions");
    if ($result && $row = $result->fetch_assoc()) {
        $stats['prefix_count'] = $row['prefix_count'];
    }
    
    // 查询转换总数
    $result = $conn->query("SELECT SUM(count) as total_transitions FROM transitions");
    if ($result && $row = $result->fetch_assoc()) {
        $stats['transition_count'] = $row['total_transitions'] ?? 0;
    }
    
    return $stats;
}

$stats = getStats();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中文文本生成模型</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', 'Segoe UI', Tahoma, sans-serif;
        }
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            color: #333;
            line-height: 1.6;
            padding: 20px;
            min-height: 100vh;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        header {
            background: linear-gradient(90deg, #4b6cb7 0%, #182848 100%);
            color: white;
            padding: 25px 30px;
            text-align: center;
        }
        h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
            font-weight: 600;
        }
        .subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
            max-width: 700px;
            margin: 0 auto;
        }
        .content {
            padding: 25px;
        }
        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 25px;
            border: 1px solid #eaeaea;
        }
        .card-title {
            font-size: 1.4rem;
            color: #2c3e50;
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 2px solid #f0f4f8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        textarea {
            width: 100%;
            min-height: 180px;
            padding: 15px;
            border: 1px solid #dce4ec;
            border-radius: 8px;
            font-size: 1.05rem;
            line-height: 1.7;
            resize: vertical;
            transition: border-color 0.3s;
        }
        textarea:focus {
            border-color: #4b6cb7;
            outline: none;
            box-shadow: 0 0 0 3px rgba(75, 108, 183, 0.2);
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #2c3e50;
        }
        input[type="number"] {
            width: 100px;
            padding: 10px 12px;
            border: 1px solid #dce4ec;
            border-radius: 6px;
            font-size: 1rem;
        }
        .btn-group {
            display: flex;
            gap: 12px;
            margin-top: 15px;
            flex-wrap: wrap;
        }
        button {
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            flex: 1;
            min-width: 120px;
        }
        .btn-train {
            background: linear-gradient(90deg, #4b6cb7 0%, #3a56a0 100%);
            color: white;
        }
        .btn-generate {
            background: linear-gradient(90deg, #2ecc71 0%, #27ae60 100%);
            color: white;
        }
        .btn-reset {
            background: linear-gradient(90deg, #e74c3c 0%, #c0392b 100%);
            color: white;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }
        .message {
            padding: 15px;
            margin: 15px 0;
            border-radius: 8px;
            text-align: center;
            font-weight: 500;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .output-box {
            background-color: #f8f9fa;
            border-left: 4px solid #4b6cb7;
            padding: 20px;
            border-radius: 0 8px 8px 0;
            margin-top: 20px;
            font-size: 1.15rem;
            line-height: 1.8;
            min-height: 120px;
            white-space: pre-wrap;
        }
        .stats {
            display: flex;
            justify-content: space-around;
            background: #f0f4f8;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            text-align: center;
        }
        .stat-item {
            flex: 1;
        }
        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #4b6cb7;
        }
        .stat-label {
            font-size: 0.95rem;
            color: #7f8c8d;
        }
        .examples {
            background: #f9f9ff;
            border: 1px dashed #d6deff;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }
        .examples h3 {
            color: #4b6cb7;
            margin-bottom: 12px;
        }
        .examples ul {
            padding-left: 25px;
        }
        .examples li {
            margin-bottom: 10px;
            line-height: 1.6;
        }
        footer {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-size: 0.9rem;
            border-top: 1px solid #eee;
        }
        @media (max-width: 768px) {
            .container {
                margin: 10px;
            }
            .btn-group {
                flex-direction: column;
            }
            .stats {
                flex-direction: column;
                gap: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>中文文本生成模型</h1>
            <p class="subtitle">基于马尔可夫链的文本生成器 | PHP + MySQL 实现</p>
        </header>
        
        <div class="content">
            <?php if ($message): ?>
                <div class="message success"><?= $message ?></div>
            <?php endif; ?>
            
            <div class="card">
                <h2 class="card-title">模型训练
                    <span style="font-size: 1rem; color: #7f8c8d;">输入中文文本训练模型</span>
                </h2>
                
                <form method="post">
                    <div class="form-group">
                        <label for="training_text">训练文本：</label>
                        <textarea 
                            id="training_text" 
                            name="training_text" 
                            placeholder="请输入中文训练文本（至少100字效果更佳）..."
                        ><?= isset($_POST['training_text']) ? htmlspecialchars($_POST['training_text']) : '' ?></textarea>
                    </div>
                    
                    <div class="btn-group">
                        <button type="submit" name="train" class="btn-train">训练模型</button>
                        <button type="submit" name="reset" class="btn-reset">重置模型</button>
                    </div>
                </form>
                
                <div class="stats">
                    <div class="stat-item">
                        <div class="stat-value"><?= $stats['prefix_count'] ?></div>
                        <div class="stat-label">学习字符数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= $stats['transition_count'] ?></div>
                        <div class="stat-label">字符关系数</div>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h2 class="card-title">文本生成
                    <span style="font-size: 1rem; color: #7f8c8d;">基于已学习的模型生成新文本</span>
                </h2>
                
                <form method="post">
                    <div class="form-group">
                        <label for="length">生成文本长度（5-200字）：</label>
                        <input 
                            type="number" 
                            id="length" 
                            name="length" 
                            value="<?= isset($_POST['length']) ? $_POST['length'] : '50' ?>" 
                            min="5" 
                            max="200"
                        >
                    </div>
                    
                    <div class="btn-group">
                        <button type="submit" name="generate" class="btn-generate">生成文本</button>
                    </div>
                </form>
                
                <?php if (!empty($generated)): ?>
                    <div class="output-box">
                        <?= nl2br(htmlspecialchars($generated)) ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="examples">
                <h3>中文训练文本示例：</h3>
                <ul>
                    <li>春天来了，万物复苏。阳光温暖地照耀着大地，花朵在微风中轻轻摇曳。小鸟在枝头欢快地歌唱，仿佛在庆祝新生命的到来。</li>
                    <li>人工智能正在改变我们的生活方式。从智能手机助手到自动驾驶汽车，科技的发展日新月异。机器学习算法通过分析海量数据，不断优化自身性能。</li>
                    <li>中华文化源远流长，博大精深。书法艺术展现了汉字的美感，传统节日承载着丰富的文化内涵。这些传统在现代社会依然焕发着生机。</li>
                </ul>
            </div>
        </div>
        
        <footer>
            <p>PHP + MySQL 文本生成模型 | 基于马尔可夫链原理 | 训练数据越多，生成效果越好</p>
        </footer>
    </div>
</body>
</html>